<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="search.userName" class="w150" placeholder="请输入用户名称" clearable />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="search.phonenumber" class="w150" placeholder="请输入手机号码" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="dictData['sys_normal_disable']" v-model="search.status" placeholder="请选择状态" class="w150"></md-dict-select>
          </el-form-item>
          <!-- <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" class="w250" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:user:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['system:user:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
        <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120">
          <template slot-scope="{ row }">
            {{row.phonenumber || '---'}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" key="status">
          <template slot-scope="{ row }">
            <el-switch v-model="row.status" active-value="0" inactive-value="1" active-color="#13ce66" inactive-color="#ff4949" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template slot-scope="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="170" fixed="right">
          <template slot-scope="{ row }">
            <template v-if="row.userId !== 1">
              <el-button size="mini" type="text" icon="el-icon-edit" v-if="['system:user:edit']" @click="handleUpdate(row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" v-if="['system:user:remove']" @click="handleDelete(row)">删除</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, row)" v-if="$isPrem(['system:user:resetPwd'])">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-if="$isPrem(['system:user:resetPwd'])">重置密码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template v-else>
              <el-tag type="primary" size="mini">超级管理员</el-tag>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="80px" label-position="right">
        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="request.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="所属部门" prop="deptId">
              <md-select-tree v-model="request.deptId" :data="dialog.deptTreeData" :defaultProps="{label: 'deptName', value: 'deptId'}" placeholder="请选择所属部门"></md-select-tree>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="request.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="request.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item v-if="request.userId == undefined" label="用户名称" prop="userName">
              <el-input v-model="request.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item v-if="request.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="request.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="用户性别" prop="sex">
              <md-dict-select :options="dictData['sys_user_sex']" v-model="request.sex" placeholder="请选择" style="width: 100%"></md-dict-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="状态" prop="status">
              <md-dict-radio-group :options="dictData['sys_normal_disable']" v-model="request.status"></md-dict-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="岗位" prop="postIds">
              <el-select v-model="request.postIds" placeholder="请选择" multiple style="width: 100%">
                <el-option v-for="item in dialog.postData" :key="item.postId" :value="item.postId" :label="item.postName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="request.roleIds" placeholder="请选择" multiple style="width: 100%">
                <el-option v-for="item in dialog.roleData" :key="item.roleId" :value="item.roleId" :label="item.roleName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="request.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<script>
import { listPageUser, insertUser, updateUser, delUser, getUser, resetUserPwd } from '@/api/system/user.service.js'
import { listRole } from '@/api/system/role.service.js'
import { listPost } from '@/api/system/post.service.js'
import { treeListDept } from '@/api/system/dept.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  name: 'MdSystemUserComponent',
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 列表数据，总条数
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加用户',
        open: false,
        postData: [], // 岗位列表
        roleData: [], // 角色列表
        deptTreeData: [] // 机构树数据
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['sys_normal_disable', 'sys_user_sex']).then(res => {
      this.dictData = res
    })

    this.getTableDataList()
  },
  methods: {
    /** 获取用户数据 */
    async getTableDataList () {
      this.tableLoading = true
      this.tableData = []

      try {
        const res = await listPageUser(this.search)

        this.tableData = res.data.items
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.userId })
    },
    /** 获取角色数据 */
    async getRoleData () {
      try {
        const res = await listRole({
          status: '0',
          orderBy: 'role_sort',
          isDesc: false
        })

        this.dialog.roleData = res.data
      } catch (error) {
        console.log(error)
      }
    },
    /** 获取岗位数据 */
    async getPostData () {
      try {
        const res = await listPost({
          status: '0',
          orderBy: 'post_sort',
          isDesc: false
        })

        this.dialog.postData = res.data
      } catch (error) {
        console.log(error)
      }
    },
    /** 获取部门数据 */
    async getDeptData () {
      try {
        const res = await treeListDept({
          status: '0',
          delFlag: '0',
          orderBy: 'order_num',
          isDesc: false
        })

        this.dialog.deptTreeData = res.data
      } catch (error) {
        console.log(error)
      }
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageIndex = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 改变用户状态事件 */
    async handleStatusChange (row) {
      try {
        const text = row.status === '0' ? '启用' : '停用'

        await this.$confirm(`确认要 ${text} ${row.userName} 用户吗？`)

        await updateUser({ userId: row.userId, status: row.status })

      } catch (error) {
        console.log(error)
        row.status = row.status === '0' ? '1' : '0'
      }
    },
    /** 更多操作 */
    handleCommand (command, row) {
      switch (command) {
        case 'handleResetPwd':
          this.handleRsetPwd(row)
          break
      }
    },
    /** 重置密码 */
    async handleRsetPwd (row) {
      try {
        const { value } = await this.$prompt(`请输入 ${row.userName} 的新密码`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
        })

        await resetUserPwd(row.userId, value)

        this.$message.success(`修改成功，新密码是：${value}`)
      } catch (error) {
        console.log(error)
      }
    },
    /** 删除 */
    async handleDelete (row) {
      try {
        const ids = row?.userId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delUser(ids)

        this.$message.success('删除成功')

        this.handleQuery()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加 */
    async handleAdd () {
      try {
        this.handleReset()
        this.getRoleData()
        this.getPostData()
        this.getDeptData()

        this.dialog.title = '添加用户'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改 */
    async handleUpdate (row) {
      try {
        this.handleReset()
        this.getRoleData()
        this.getPostData()
        this.getDeptData()

        const res = await getUser(row.userId)

        const data = res.data.user
        data.roleIds = res.data.roleIds || []
        data.postIds = res.data.postIds || []

        this.request = data

        this.dialog.open = true

        this.dialog.title = '修改用户'

      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          await (params.userId === undefined ? insertUser : updateUser)(params)

          this.$message.success(params.userId === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false;

          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}
// 搜索条件
const searchParams = {
  deptId: 0,
  userName: undefined,
  nickName: undefined,
  userType: '00',
  email: undefined,
  phonenumber: undefined,
  sex: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  pageIndex: 1,
  pageSize: 10
}

// 添加/编辑请求参数
const requestParams = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  userType: '00',
  email: undefined,
  phonenumber: undefined,
  sex: '0',
  avatar: undefined,
  password: undefined,
  status: '0',
  remark: undefined,
  roleIds: [],
  postIds: []
}

// 表单验证
const rules = {
  userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }, { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }, { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
  postIds: [{ required: true, message: '请选择岗位', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
}
</script>